import { createRouter, createWebHashHistory } from "vue-router";
import { localStorageUtils, useI18n, NotFound, NoPermission } from "@gonsin/gview";
import GLicense from "@gonsin/glicense";
import { MessagePlugin } from "tdesign-vue-next";
import { LOCAL_USER } from "~/constant";

const router = createRouter({
	history: createWebHashHistory(import.meta.env.BASE_URL),
	routes: [
		{ path: "/", redirect: "/view" },
		{
			path: "/view",
			name: "view",
			component: () => import("@/views/HomeView.vue"),
		},
		{
			path: "/login",
			name: "login",
			component: () => import("@/views/LoginView.vue"),
		},
		{
			path: "/license",
			name: "license",
			component: GLicense,
		},
		{
			path: "/HomePage",
			name: "HomePage",
			component: () => import("@/views/HomePage.vue"),
		},

		{
			path: "/404",
			name: "404NotFound",
			component: NotFound,
		},
		{
			path: "/403",
			name: "403Forbidden",
			component: NoPermission,
		},
		{
			path: "/:pathMatch(.*)",
			redirect: "/404",
		},
	],
});

router.beforeEach((to, from, next) => {
	const { T } = useI18n();
	const loginStatus = localStorageUtils.getItem(LOCAL_USER);

	const routerExcludeList = ["/login", "/license", "/showSlogan"];

	if (routerExcludeList.includes(to.path)) {
		if (to.path == "/login" && loginStatus) {
			return next("/view");
		}

		return next();
	}

	if (!loginStatus && to.path !== "/login") {
		// MessagePlugin.warning(T.t("请先登录"));
		return next({
			path: "/login",
			query: {
				redirect: encodeURIComponent(to.fullPath),
			},
		});
	}

	next();
});

export default router;
